var app = getApp();
var content = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    input_list: [{ "type": "textarea", "title": "发帖内容", "name": "content" }],
    add_url: "https://www.58zltc.com/api.php/Quan/add",
    index_url: "/pages/quan/quan",
    token: null,
    video_path: null,
    pics: [],
    topic_list: []
  },
  onLoad: function (options) {
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    let that = this;
    this.setData({
      add_url: this.data.add_url,
      token: extConfig.appid
    })
    if(options.circleid){
      this.setData({
        circleid: options.circleid
      })
      return;
    }
    app.ihttpGet('https://www.58zltc.com/api.php/Quan/topicList', function (res) {
      that.setData({
        topic_list: res.data
      })
    });
    //发帖付费逻辑
    // app.ihttpGet('https://www.58zltc.com/api.php/Quan/getAddTiePayInfo/openid/' + app.globalData.openid, function (res) {
    //   console.log(res.data)
    //   that.setData({
    //     TiePayInfo: res.data
    //   })
    // });
  },
  backto: function (e) {
    wx.navigateBack({})
  },

  onReady: function () {
    let that = this;
    wx.getLocation({
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })
  },
  onShow: function(){
    let that = this;
    wx.getStorage({
      key: 'video_path',
      success: function(res) {
        if(res.data){
          that.setData({
            video_path: res.data
          })
          wx.removeStorage({
            key: 'video_path',
            success: function(res) {},
          })
        }
      },
    })
  },
  textboxBlur:function(e){
    content = e.detail.value;
  },
  setTopic: function(e){
    const topic = e.currentTarget.dataset.topic;
    var new_content = '#'+topic+'#'+content;
    var input_list = this.data.input_list;
    input_list[0].value = new_content;
    this.setData({
      input_list: input_list
    })
  },
  formSubmit: function (e) {
    // console.log(e.detail.value);
    app.addFormId(e.detail.formId);
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let that = this;
    var post_data = e.detail.value;
    var data = this.data;
    post_data.openid = app.globalData.openid;
    post_data.pics = data.pics;
    post_data.latitude = data.latitude;
    post_data.longitude = data.longitude;
    if(data.circleid){
      post_data.circleid = data.circleid;
      that.setData({
        add_url:"https://www.58zltc.com/api.php/Quan/circle_content"
      })
    }
    if(!data.video_path){
      that.ihttpPost(post_data);
    }else{
      // app.ihttpGet('https://www.58zltc.com/api.php/Index/uploadVideo/filePath/' + data.video_path , function (res) {
      //   console.log(res);
      // });
      wx.uploadFile({
        url: 'https://www.58zltc.com/api.php/Index/uploadVideo?token=' + that.data.token, //仅为示例，非真实的接口地址
        filePath: data.video_path,
        name: 'file',
        success: function (res) {
          console.log(res);
            var out = JSON.parse(res.data);
            post_data.video_path = out.data.domain;
            post_data.video_thumb = out.data.thumb;
            that.ihttpPost(post_data);
        }
      })
    }
  },
  ihttpPost: function(post_data){
    var t = this
    app.ihttpPost(this.data.add_url, post_data, function(res){
      if (res.data.err_code === 400) {
        wx.showToast({
          title: res.data.err_msg,
        })
      } else if (res.data.err_code === 0) {
        wx.showToast({
          title: res.data.err_msg,
          icon: 'success'
        })
        setTimeout(function () {
          app.globalData.add = "add"
          if(t.data.circleid){
            wx.navigateTo({
              url: '/pages/quan/quan/details?id='+t.data.circleid,
            })
          }else{
            //wx.navigateBack({})
            //发布完直接跳优惠券页面
            wx.navigateTo({
              url: '/pages/shop/coupon/coupon',
            })
          }
        }, 1500)
      } else {
        wx.requestPayment({
          'appId': res.data.appId,
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': res => {
            if (res.errMsg == 'requestPayment:ok') {
              wx.navigateTo({
                url: data.index_url,
              })
            }
          }
        })
      }
    })
  },
  delImg: function(e){
    const idx = e.currentTarget.dataset.idx;
    var pics = this.data.pics;
    pics.splice(idx,1);
    this.setData({
      pics:pics
    })
  },
  bindUpload: function(e){
    let that = this;
    var data = that.data;
    if (data.pics.length===0 && !data.video_path){
      var itemList = ['拍照', '拍小视频', '从相册选择照片', '从相册选择小视频'];
    } else if (data.pics.length === 0){
      var itemList = ['拍小视频', '从相册选择小视频'];
    }else{
      var itemList = ['拍照', '从相册选择照片'];
    }
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        var item = itemList[res.tapIndex];
        switch (item){
          case '拍照':
            that.chooseImage('camera');
            break;
          case '拍小视频':
            that.chooseVideo('camera');
            // wx.navigateTo({
            //   url: 'camera/camera',
            // })
            break;
          case '从相册选择照片':
            that.chooseImage('album');
            break;
          case '从相册选择小视频':
            that.chooseVideo('album');
            break;
        }
        console.log(res.tapIndex)
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  chooseImage: function(type){
    let that = this;
    var pics_length = that.data.pics.length +1 ;
    if(pics_length > 9){
      wx.showToast({
        title: '最多只能上传9张图片',
        icon:"none",
        duration: 2000
      })  
    }else{
      wx.chooseImage({
        sourceType: [type],
        count: 9,
        success: function (res) {
          var tempFilePaths = res.tempFilePaths;
          wx.showLoading({
            title: '图片上传中……',
          })
          tempFilePaths.forEach(function (item, idx) {
            wx.uploadFile({
              url: 'https://www.58zltc.com/api.php/Index/uploadImage?token=' + that.data.token, //仅为示例，非真实的接口地址
              filePath: item,
              name: 'file',
              success: function (res) {
                console.log(res)
                var out = JSON.parse(res.data);
                if (out.err_code > 0) {
                  wx.showToast({
                    title: '上传失败！',
                  })
                } else {
                  var pics = that.data.pics;
                  var file_name = out.data.domain;
                  pics.push(file_name);
                  that.setData({
                    pics: pics
                  })
                }

                if (idx == tempFilePaths.length - 1) {
                  wx.hideLoading();
                }
                //do something
              }
            })
          })
        },
      })
    }
    
  },
  chooseVideo: function(type){
    let that =this;
    wx.chooseVideo({
      sourceType: [type],
      maxDuration: 10,
      compressed: true,
      success: function(res){
        if (res.duration > 10 || res.size / 1024 / 1024 >= 5){
          wx.showModal({
            title: '提示',
            content: '上传视频不能超过10秒',
            showCancel: false,
            confirmText: '我知道了'
          })
        }else{
          that.setData({
            video_path: res.tempFilePath,
          })
          console.log(res);
        }
      }
    })
  },
})